package com.zxk.blog.interceptor;

import com.zxk.api.service.UserService;
import com.zxk.core.common.model.UserInfo;
import com.zxk.core.common.util.CommonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String name = request.getParameter("name");
        String pwd = request.getParameter("pwd");
        List<UserInfo> userInfos = userService.queryUserInfo(name);
        if(userInfos.size() != 1) {
            return false;
        } else {
            System.out.println(CommonUtils.MD5(pwd));
            if( CommonUtils.MD5(pwd).equals(userInfos.get(0).getPwd())) {
                HttpSession session = request.getSession();
                session.setAttribute("name",name);
                return true;
            }
            return false;
        }
    }
}
